


import React, { useContext, useImperativeHandle, useState } from "react";
import { Space, message, Checkbox, Select, Input, Button, Radio, Form, Tabs } from "antd"
import SelectTabsIndex from "./selectTabsIndex";
import { createTask } from "@/api/task";
import { getUrlParam } from "@/utils/getUrlData";
import ZtreeSelect from "../zc-treeSelect/authTreeSelect";
import { Context } from "@/app-context/main-context";

const initCodeTarget = JSON.stringify({
    syntTarget: [],
    baseTarget: [],
    vehTarget: [],
    custActTarget: [],
    fxqTarget: [],
    insTarget: [],
    clmTarget: []

})


let tagCodes = JSON.parse(sessionStorage.codeTarget || initCodeTarget)


const PanelOfCreateTask = ({ cancel = () => { }, onRef, treeData = [], sourceData = [] }) => {
    const [form] = Form.useForm();
    const [comObject, setComObject] = useState({});
    const [confirmLoading, setConfirmLoading] = useState(false);
    const { condition } = useContext(Context)
    const { createBy, operateBy } = condition
    // 点击取消或者关闭窗口
    const onCancel = () => {
        cancel()
    }

    // 点击确定的时候 提交一个下载任务请求
    const createDownLoad = async (values) => {

        // console.log("指标列表长度", statJobDtList.length, "\n列表：\n", statJobDtList)
        if (statJobDtList.length === 0) {
            return;
        }
        setConfirmLoading(true)
        const { jobName, statType, statDate } = values


        createTask({
            params: {
                statTask: {
                    createBy,
                    operateBy,
                    jobName,
                    statType,
                    statDate,
                    comCode: comObject.comCode||"",
                    unitLevel: comObject.unitLevel||"",
                    jobStatus: "0",
                    statJobDtList: statJobDtList

                }
            },
            success: (res) => {
                if (res.responseCode === "0000") {
                    message.success(res.responseMsg)
                    form.resetFields();
                    onCancel();
                    clearAllCheck();//重置清空
                } else {
                    message.warning(res.responseMsg)
                }

            },
            failure: (error) => {

            },
            complate: () => {
                setConfirmLoading(false)
                setTimeVal("01");//重置
            }
        })

    }



    // 年月筛选框相关start
    const [timeInputPlaceHolder, setTimeInputPlaceHolder] = useState("输入格式：如2022年，则直接输入2022")
    const [timeVal, setTimeVal] = useState("01")

    const changeTime = (e) => {
        console.log("年或是月？", e.target.value)
        setTimeVal(e.target.value)
        if (e.target.value === "01") {
            setTimeInputPlaceHolder("输入格式：如2022年，则直接输入2022")
        } else {
            setTimeInputPlaceHolder("输入格式：如2022年2月，则直接输入202202")
        }
    }



    // statJobDtList 用来存放选择的指标列表
    const [statJobDtList, setStatJobDtList] = useState([]);

    // 计算当前模块有多少个指标被选中
    const getModuleCount = (list = []) => {
        var count = 0;
        // console.log(statJobDtList.length, list.length)
        for (var i = 0; i < list.length; i++) {
            for (var j = 0; j < statJobDtList.length; j++) {
                if (list[i].cval === statJobDtList[j].targetCode) {
                    count++
                    break;
                }
            }

        }
        return count;
    }

    const onOk = () => {
        form.validateFields()
            .then((values) => {
                createDownLoad(values)
            })
            .catch((info) => {
                console.log('Validate Failed:', info.values);
            });
    }

    // 计数器 初始为0，其他控制勾选的子组件监听它，如果它变化了，就及时取消勾选
    const [count, setCount] = useState(0);

    // 清除全部已选中的指标
    const clearAllCheck = () => {
        setStatJobDtList([]);
        setCount(count + 1)
    }

    const propsConfig = {
        form,
        count,
        setCount
    }


    // 向外暴露一些方法属性
    useImperativeHandle(onRef, () => ({
        // queryUnitList, //查询机构列表暴露给父组件，二级机构列表在父组件中查询，提升弹窗窗口性能。
    }))

    return (
        <>
            <Form
                form={form}

                layout="vertical"
                name="form_in_modal"
                initialValues={{
                    statType: "01",
                    statDate: (new Date()).getFullYear()
                }}
            // onValuesChange={onFieldsChange}
            >
                <Form.Item
                    name="jobName"
                    label="任务名称"
                    rules={[
                        {
                            required: true,
                            message: '必填任务名称',
                        },
                    ]}
                >
                    <Input allowClear placeholder="输入一个自定义的任务名称" value="测试任务" />
                </Form.Item  >
                <Form.Item
                    name="comCode"
                    rules={[
                        {
                            required: true,
                            message: '必选项',
                        },
                    ]}
                    label="机构筛选"
                    allowClear={false}
                >
                    <ZtreeSelect
                        fieldNames={{
                                label: "comSName",
                                value: "comCode",
                                unitLevel: "unitLevel",
                                children: "untList"
                            }}
                            treeData={treeData}
                            labelInValue={true}
                            onSelect={(value, options) => {
                                setComObject({...options})
                            }}
                    />
                </Form.Item>
                <Form.Item
                    name="sourceCode"
                    label="来源渠道"
                    allowClear={false}
                >
                    <Select
                        disabled={true}
                        placeholder="来源渠道筛选暂不可用"
                        labelInValue={true}
                        showArrow={true}
                        showSearch={true}
                        // allowClear
                        filterOption={(input, option) => (option?.comSName ?? '').includes(input)}
                        filterSort={(optionA, optionB) =>
                            (optionA?.comSName ?? '').toLowerCase().localeCompare((optionB?.comSName ?? '').toLowerCase())}
                        options={sourceData}
                    />
                </Form.Item>
                <Form.Item
                    label="时间类型"
                    name={"statType"}
                >
                    <Radio.Group
                        onChange={changeTime}
                        defaultValue="01"
                        value={timeVal}>
                        <Radio value="01">年</Radio>
                        <Radio value="02">月</Radio>
                    </Radio.Group>
                </Form.Item>
                {
                    timeVal === "01" ? <Form.Item
                        label="统计年份"
                        name="statDate"
                        rules={[
                            {
                                required: true,
                                pattern: /^\d{4}$/,
                                message: '时间校验未通过，年份格式为：YYYY，如2022年，请输入：2022',
                            },
                        ]}
                    >

                        <Input
                            placeholder={timeInputPlaceHolder}
                        // style={{ width: 400 }}
                        >
                        </Input>
                    </Form.Item> :
                        <Form.Item
                            label="统计月份"
                            name="statDate"
                            rules={[
                                {
                                    required: true,
                                    pattern: /^\d{6}$/,
                                    message: '时间校验未通过，月份格式为：YYYYMM，如2022年8月，请输入：202208',
                                },
                            ]}
                        >

                            <Input
                                placeholder={timeInputPlaceHolder}
                            // style={{ width: 400 }}
                            >
                            </Input>
                        </Form.Item>
                }

                <Space
                    style={{ color: statJobDtList.length === 0 ? "red" : "unset" }}
                >{`* 已选择${statJobDtList.length}个指标`}{statJobDtList.length > 0 ? <Button onClick={() => clearAllCheck()} type="link">清除已选指标</Button> : null}</Space>
                <Checkbox.Group
                    // onChange={getCheckCount}
                    style={{ width: "100%" }}
                >
                    <Tabs
                        defaultActiveKey="0"
                        // tabPosition="left"
                        // style={{
                        //     height: 300
                        // }}
                        items={[
                            {
                                label: `综合指标（${getModuleCount(tagCodes.syntTarget)}）`,
                                key: '0',
                                children: <SelectTabsIndex
                                    module="syntTarget"
                                    statJobDtList={statJobDtList}
                                    setStatJobDtList={setStatJobDtList}
                                    options={tagCodes.syntTarget}
                                    form={form}
                                    index={"0"}
                                    {...propsConfig}
                                />,
                            },
                            {
                                label: `基本指标（${getModuleCount(tagCodes.baseTarget)}）`,
                                key: '1',
                                children: <SelectTabsIndex
                                    module="baseTarget"
                                    statJobDtList={statJobDtList}
                                    setStatJobDtList={setStatJobDtList}
                                    options={tagCodes.baseTarget}
                                    form={form}
                                    index={"1"}
                                    {...propsConfig}
                                />,
                            },
                            {
                                label: `车辆指标（${getModuleCount(tagCodes.vehTarget)}）`,
                                key: '2',
                                children: <SelectTabsIndex
                                    module="vehTarget"
                                    statJobDtList={statJobDtList}
                                    setStatJobDtList={setStatJobDtList}
                                    options={tagCodes.vehTarget}
                                    form={form}
                                    index={"2"}
                                    {...propsConfig}
                                />,
                            },
                            {
                                label: `行为指标（${getModuleCount(tagCodes.custActTarget)}）`,
                                key: '3',
                                children: <SelectTabsIndex
                                    module="custActTarget"
                                    statJobDtList={statJobDtList}
                                    setStatJobDtList={setStatJobDtList}
                                    options={tagCodes.custActTarget}
                                    form={form}
                                    index={"3"}
                                    {...propsConfig}
                                />,
                            },
                            {
                                label: `反洗钱指标（${getModuleCount(tagCodes.fxqTarget)}）`,
                                key: '4',
                                children: <SelectTabsIndex
                                    module="fxqTarget"
                                    statJobDtList={statJobDtList}
                                    setStatJobDtList={setStatJobDtList}
                                    options={tagCodes.fxqTarget}
                                    form={form}
                                    index={"4"}
                                    {...propsConfig}
                                />,
                            },
                            {
                                label: `承保指标（${getModuleCount(tagCodes.insTarget)}）`,
                                key: '5',
                                children: <SelectTabsIndex
                                    module="insTarget"
                                    statJobDtList={statJobDtList}
                                    setStatJobDtList={setStatJobDtList}
                                    options={tagCodes.insTarget}
                                    form={form}
                                    index={"5"}
                                    {...propsConfig}
                                />,
                            },
                            {
                                label: `理赔指标（${getModuleCount(tagCodes.clmTarget)}）`,
                                key: '6',
                                children: <SelectTabsIndex
                                    module="clmTarget"
                                    statJobDtList={statJobDtList}
                                    setStatJobDtList={setStatJobDtList}
                                    options={tagCodes.clmTarget}
                                    form={form}
                                    index={"6"}
                                    {...propsConfig}
                                />,
                            },

                        ]}
                    />
                </Checkbox.Group>
                <div style={{ display: "flex", padding: "10px 0", justifyContent: "end" }}>
                    <Space>
                        <Button onClick={onCancel}>取消</Button>
                        <Button key="submit" type="primary" onClick={onOk}>
                            确定
                        </Button>
                    </Space>
                </div>
            </Form>
        </>
    )
}
export default PanelOfCreateTask;